package com.trf.springcloud.controller;

import com.trf.springcloud.pojo.Dept;
import com.trf.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 小小唐
 * @Date 2022/5/19-星期四-21:22
 *
 * 提供Restful服务
 */
@RestController
public class DeptController {

    //Controller层调用Service层
    @Autowired
    private DeptService deptService;

    //获取配置的信息，得到具体的微服务  （选择接口）
    @Autowired
    private DiscoveryClient discoveryClient;

    //调用服务
    //@PostMapping("/dept/add")注意网页url默认使用get方式访问
    @RequestMapping("/dept/add")
    public boolean addDept(Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
        return deptService.queryById(id);
    }

    @GetMapping("/dept/list")
    public List<Dept> queryAll(){
        return deptService.queryAll();
    }


    /**
     * 注册进来的微服务，获取一些信息
     *
     * @return
     */
    @GetMapping("/dept/discovery")
    public Object discovery(){
        //获取微服务的列表清单
        List<String> services = discoveryClient.getServices();
        System.out.println("discovery==>services:"+services);

        //得到一个具体的微服务信息，通过具体的微服务id，applicationName:
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");

        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri()+"\t"+
                    instance.getServiceId()
            );
        }
        return this.discoveryClient;
    }

}
